﻿/*---------function-----------*/

//加入收藏
function addFavorite() {
    try {
        window.external.addFavorite(window.location, document.title);
    }
    catch (e) {
        try {
            window.sidebar.addPanel(document.title, window.location, "");
        }
        catch (e) {
            alert("你的浏览器不支持自动加入收藏 请按Ctrl+D键加入收藏");
        }
    }
}

function base64Encode(blob, callback) {
    var reader = new FileReader();
    reader.readAsDataURL(blob);
    reader.onload = function (e) {
        callback(e.target.result);
    }
}

function base64Decode(str) {
    //str不带声明
    var byteString = atob(str);
    var uint8Array = new Uint8Array(byteString.length);
    for (var index = 0; index < byteString.length; index++) {
        uint8Array[index] = byteString.charCodeAt(index);
    }
    return uint8Array;
}

//检查是否是图片
function isImage(url) {
    return url.substring(url.lastIndexOf(".")).toLowerCase().match(/.png|.jpg|.jpeg/);
}

function log(msg) {
    $("#log").log(msg);
}

//字符串填充
function stringFormat() {
    var args = arguments;
    return args[0].replace(/\{(\d+)\}/g, function (m, i) { return args[i * 1 + 1]; });
}

//页面跳转
function relocate(url) {
    window.location.href = url;
}

//页面刷新
function refresh() {
    window.location.href = window.location.href;
}

//判断布尔字符串
function parseBoolen(obj) {
    if (obj == "True" || obj == "true" || obj == "TRUE")
        return true;
    else
        return false;
}

//循环调用
function setIntervalOnce(callback, interval) {
    callback();
    setInterval(callback, interval);
}

//消息 注意引用common.css
function showMessage(msg) {
    var messageDialog = $("#messageDialog");
    if (messageDialog.length == 0) {
        $("body").append('<div id="messageDialog"><span id="messageContent"></span></div>');
        messageDialog = $("#messageDialog");
    }
    var messageContent = $("#messageContent");
    messageContent.html(msg);
    messageDialog.show();
    setTimeout(function () {
        messageDialog.hide();
    }, 1000);
}

//遮罩 注意引用common.css
function showLoading() {
    var loadingDialog = $("#loadingDialog");
    if (loadingDialog.length == 0) {
        $("body").append('<div id="loadingDialog"><div></div><img src="/common/loading.gif" /></div>');
        loadingDialog = $("#loadingDialog");
    }
    loadingDialog.show();
}

function hideLoading() {
    var loadingDialog = $("#loadingDialog");
    if (loadingDialog.length > 0)
        loadingDialog.hide();
}

//通知
function showNotification(msg) {
    //判断兼容
    if (window.Notification) {
        //判断权限
        if (window.Notification.permission == "granted") {
            var notification = new Notification(msg);
            setTimeout(function () { notification.close(); }, 5000);
        } else {
            window.Notification.requestPermission();
        }
    }
    else
        alert('你的浏览器不支持此消息提示功能，请使用chrome内核的浏览器！');
}

/*-------对象扩展------------*/
//对象扩展会导致jQuery选择器在选择不存在的对象时异常，引发matchExpr[type].exec is not a function
//toJsonString
//if (Object.prototype.toJsonString == undefined) {
//    Object.prototype.toJsonString = function () {
//        try {
//            return JSON.stringify(this);
//        }
//        //这个去掉会引发Uncaught TypeError: Converting circular structure to JSON
//        catch{ }
//    }
//}

/*----------$.---------*/

//从timestamp中获取时间信息
$.fromStamp = function (stamp) {
    var newDate = new Date();
    newDate.setTime(stamp * 1000);
    return newDate.getFullYear() + "-" + newDate.getMonth() + "-" + newDate.getDay() + " " + newDate.getHours() + ":" + newDate.getMinutes() + ":" + newDate.getSeconds();
};

//输入框的值含空
$.valueEmpty = function () {
    var args = arguments;
    var result = false;
    $(args).each(function (index, item) {
        if (!result && $(item).val() == '')
            result = true;
    });
    return result;
};

//两个输入框的值不一样
$.valueDiff = function (selector1, selector2) {
    return $(selector1).val() != $(selector2).val();
};

//从文件导入html
$.loadWrite = function (url) {
    $.ajax({
        async: false,
        type: "GET",
        url: url,
        success: function (html) {
            document.writeln(html);
        },
        error: function (error) {
            alert(error.statusText);
        }
    });
};

//消息提示
$.message = function (msg) {
    showMessage(msg);
};

//载入遮罩
$.loading = function () {
    showMessage("loading...");
    showLoading();
};

//关闭遮罩
$.loadingHide = function () {
    hideLoading();
};

//循环调用
$.loop = function (callback, intervalSeconds) {
    setIntervalOnce(callback, intervalSeconds * 1000);
};

//get
$.httpGet = function (url, callback) {
    $.loading();
    $.ajax({
        async: true,
        type: "GET",
        url: url,
        success: function (data) {
            $.loadingHide();
            callback(data);
        },
        error: function (error) {
            $.loadingHide();
            $.message("ajax error: " + error.statusText);
        }
    });
};

//post any
$.postAny = function (api, data, callback, contentType) {
    //$.loading();
    $.ajax({
        async: true,
        type: "POST",
        url: api,
        contentType: contentType,
        data: data,
        success: function (result) {
            callback(result);
            //$.loadingHide();
        },
        error: function (error) {
            //$.loadingHide();
            $.message("ajax error: " + error.statusText);
            //$.alert(error.statusText);
            //alert(error.statusText);
        }
    });
};

//post form
$.postForm = function (api, struct, callback) {
    $.postAny(api, struct, callback, "application/x-www-form-urlencoded");
};

//post json
$.postJson = function (api, struct, callback) {
    $.postAny(api, JSON.stringify(struct), callback, "application/json");
};

//post text
$.postText = function (api, text, callback) {
    //asp.net.core.api 不支持 [FromfBody]string，用 Request.GetBodyText() 代替
    //$.postAny(api, text, callback, "text/html");
    $.postAny(api, text, callback, "text/plain");
    //$.postAny(api, text, callback, "text/richtext");
    //$.postAny(api, text, callback, "text/xml");
    //$.postAny(api, text, callback, "application/json");
};

//post null
$.postNull = function (api, callback) {
    $.postForm(api, null, callback);
};

//上传文件
$.postFile = function (api, eleId, callback) {
    $.loading();
    var data = new FormData();
    data.append("file", document.getElementById(eleId).files[0]);
    $.ajax({
        type: "POST",
        url: api,
        contentType: false, //tell jQuery not to set contentType
        data: data,
        processData: false, //tell jQuery not to process the data
        success: function (data) {
            callback(data);
            $.loadingHide();
        },
        error: function (error) {
            $.loadingHide();
            $.message("ajax error: " + error.statusText);
        }
    });
};

//限制4M
$.postFileByBase64 = function (api, eleId, callback) {
    $.loading();
    var file = document.getElementById(eleId).files[0];
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function (e) {
        var base64 = this.result.substring(this.result.indexOf(',') + 1);
        var data = "name=" + file.name + "&" + "base64=" + base64;
        $.postForm(api, data, callback);
    }
};

//限制100M
$.postFileByJson = function (api, eleId, callback) {
    $.loading();
    var file = document.getElementById(eleId).files[0];
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function (e) {
        var base64 = this.result.substring(this.result.indexOf(',') + 1);
        $.postJson(api, { Name: file.name, base64: base64 }, callback);
    }
};

//post
$.httpPost = $.postForm;

//delete
$.httpDelete = function (url, callback) {
    $.loading();
    $.ajax({
        async: true,
        type: "DELETE",
        url: url,
        success: function (data) {
            $.loadingHide();
            callback(data);
        },
        error: function (error) {
            $.loadingHide();
            $.message("ajax error: " + error.statusText);
        }
    });
};

$.delete = $.httpDelete;

/*----------$.fn.-----------*/

$.fn.valInsert = function (val) {
    $(this).val(val + $(this).val());
};

$.fn.valAppend = function (val) {
    $(this).val($(this).val() + val);
};

var logCount = 0;

$.fn.log = function (val) {
    $(this).valInsert(stringFormat("({0})[{1}]\r\n", ++logCount, new Date()) + val + "\r\n\r\n");
};

//获取/设置表单
$.fn.json = function (data) {
    if (data == undefined) {
        var json = {};
        $(this).find("[name]").each(function (index, item) {
            switch (item.type) {
                case "checkbox":
                    json[item.name] = item.checked;
                    break;
                default:
                    json[item.name] = item.value;
            }
        });
        return json;
    }
    else {
        var json = {};
        for (var key in data)
            json[key.toLowerCase()] = data[key];
        $(this).find("[name]").each(function (index, item) {
            switch (item.type) {
                case "checkbox":
                    item.checked = json[item.name.toLowerCase()];
                    break;
                default:
                    item.value = json[item.name.toLowerCase()];
            }
        });
    }
};

//输入框清空
$.fn.clearVal = function () {
    $(this).val('');
};

//输入框只读
$.fn.readOnly = function () {
    $(this).attr("disabled", "disabled");
};

//输入框可读写
$.fn.readWrite = function () {
    $(this).removeAttr("disabled");
};

//判断是否隐藏
$.fn.isHidden = function () {
    return $(this).is(":hidden");
}

//checkbox状态
$.fn.isChecked = function () {
    return $(this).is(":checked");
};

//checkbox选中
$.fn.addChecked = function () {
    $(this).prop("checked", true);
};

//checkbox取消选中
$.fn.removeChecked = function () {
    $(this).prop("checked", false);
};

//只读
$.fn.readOnly = function () {
    $(this).attr("readonly", "readonly");
};

//读写
$.fn.readWrite = function () {
    $(this).removeAttr("readonly");
};

//禁用
$.fn.disable = function () {
    $(this).addClass("disable");
};

//启用
$.fn.enable = function () {
    $(this).removeClass("disable");
};

//获取整形
$.fn.int = function () {
    var value = parseInt($(this).val());
    if (isNaN(value))
        return 0;
    return value;
};

//checkbox选中开关
$.fn.toggleChecked = function () {
    $(this).each(function () {
        if ($(this).isChecked())
            $(this).removeChecked()
        else
            $(this).addChecked();
    });
};

//checkbox集里所有选中的checkbox的param
$.fn.checkedIds = function () {
    var ids = "";
    $(this).children("span").children("input[type=checkbox]").each(function () {
        if (!$(this).isHidden() && $(this).isChecked())
            ids += $(this).attr("param") + ',';
    });
    return ids;
};

//select获取option
$.fn.selectFilt = function (type) {
    $(this).children("option").hide();
    if (type == -1)
        $(this).children("option").show();
    else {
        $(this).children("option[type=" + type + "]").show();
        $(this).val($(this).children("option[type=" + type + "]").val());
    }
};

//select获取option
$.fn.option = function (value) {
    if (value == undefined)
        return $(this).children("option[value=" + $(this).val() + "]");
    return $(this).children("option[value=" + value + "]");
};

//select获取option的文本
$.fn.optionText = function (value) {
    return $(this).option(value).html();
};

//select同步select
$.fn.syncSelect = function (select) {
    var option = $(this).option($(select).val());
    if (option.length > 0)
        $(this).val($(select).val());
};

//html匹配select的文本
$.fn.mateSelect = function (select) {
    $(this).each(function () {
        var text = $(select).optionText($(this).html());
        if (text != undefined && text != '')
            $(this).html(text);
    });
};

/*--------$(document).ready-----------*/

$(document).ready(function () {
    //值同步
    $("[valuesync]").each(function () {
        var item = $(this);
        $("#" + item.attr("valuesync")).change(function () {
            item.val($(this).val());
            item.html($(this).val());
        });
    });

    //点击事件同步
    $("[clicksync]").click(function () {
        $("#" + $(this).attr("clicksync")).click();
    });

    //图片上传预览
    //示例 <img id="preview" /><input type="file" preview="preview" />
    $('input[type=file][preview]').on('change', function () {
        if (isImage($(this).val()))
            $('#' + $(this).attr("preview")).attr('src', window.URL.createObjectURL(this.files[0]));
    });

    //格式化数字输入框
    $(".number").each(function () {
        if ($(this).attr("placeholder") == undefined)
            $(this).attr("placeholder", "仅限数字")
        $(this).keyup(function () {
            var val = parseInt($(this).val(), 10);
            if (isNaN(val))
                val = ''
            $(this).val(val);
        })
    });

    //文件上传
    $("[click=upload]").click(function () {
        var api = $(this).attr("api");
        var file = document.createElement("input");
        file.type = "file";
        $(file).change(function () {
            var form = new FormData();
            form.append("file", file.files[0]);
            $.ajax({
                url: api,
                type: 'POST',
                data: form,
                async: false,
                cache: false,
                contentType: false,
                processData: false,
                success: function (result) {
                    alert(result);
                },
                error: function (info) {
                    alert("error: " + info.status);
                }
            });
        });
        $(file).click();
    });

    //文本导入
    $("[click=import]").click(function () {
        var input = $($(this).attr("target"));
        var file = document.createElement("input");
        file.type = "file";
        $(file).change(function () {
            var reader = new FileReader();
            reader.onload = function () {
                input.val(reader.result);
            };
            reader.readAsText(file.files[0]);
        });
        $(file).click();
    });

    //访问api
    $("[api]").click(function () {
        $.get($(this).attr("api"), function (result) {
            if (result != null && result != '')
                alert(result.Message);
        });
    });
    $("[api-refresh]").click(function () {
        $.get($(this).attr("api-refresh"), function (result) {
            if (result != null && result != '')
                alert(result.Message);
            refresh();
        });
    });

    //跳转url
    $("[url-locate]").click(function () {
        window.location.href = $(this).attr("url-locate");
    });

    //新开启url
    $("[url-open]").click(function () {
        window.open($(this).attr("url-open"));
    });

    //访问url并刷新页面
    $("[url-refresh]").click(function () {
        $.get($(this).attr("url-refresh"), function () {
            refresh();
        });
    });

    //仅访问url
    $("[url-null]").click(function () {
        $.get($(this).attr("url-null"));
    });

    $("#WebSocketLog").each(function () {
        var textarea = $(this);
        var url = textarea.attr("url");
        var client = new WebSocket(url);
        client.onopen = function () {
            textarea.log("WebSocketLog open! " + url);
        };
        client.onclose = function () {
            textarea.log("WebSocketLog close!");
        };
        client.onmessage = function (event) {
            textarea.log(event.data);
        };
    });
});